package com.daxt.service.impl;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daxt.common.util.DateUtil;
import com.daxt.common.util.RSAUtil;
import com.daxt.common.util.SdkUtil;
import com.daxt.mapper.sys.*;
import com.daxt.model.dic.UserClassifyType;
import com.daxt.model.dic.VersionsMarkType;
import com.daxt.model.dto.Classifys;
import com.daxt.model.service.base.vo.*;
import com.daxt.utils.BaseUtil;
import com.sxlq.dmapi.model.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxt.base.common.util.JwtUtil;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.base.common.util.TokenInfo;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.common.util.Md5Util;
import com.daxt.model.dic.ClientType;
import com.daxt.model.service.base.param.EditUser;
import com.daxt.model.service.base.param.LoginInfo;
import com.daxt.model.service.base.result.UserInfo;
import com.daxt.service.UserService;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, BaseUser> implements UserService {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private UserClassifyMapper userClassifyMapper;
    @Autowired
    private RoleFunctionMapper roleFunctionMapper;
    @Autowired
    private FunctionMapper functionMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private UserDeptMapper userDeptMapper;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private UserPostMapper userPostMapper;
    @Autowired
    private UserFondsMapper userFondsMapper;

    @Autowired
    private RsaMapper rsaMapper;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<UserInfo> login(LoginInfo loginInfo, HttpServletRequest request) {

        QueryWrapper<BaseUser> queryWrapper = new QueryWrapper<BaseUser>();
        queryWrapper.eq("username", loginInfo.getUsername());
        List<BaseUser> baseUsers = userMapper.selectList(queryWrapper);

        Result<UserInfo> validateParam = ValidateParam(loginInfo);
        if (validateParam != null) {
            return validateParam;
        } else if (baseUsers == null || baseUsers.size() == 0) {
            return ResultUtil.data(ResultCode.USERNAME_ERROR.getCode(), ResultCode.USERNAME_ERROR.getMes(), null);
        } else {
            if (!"0".equals(loginInfo.getLoginType()) && !"1".equals(loginInfo.getLoginType()) && !"2".equals(loginInfo.getLoginType())) {
                loginInfo.setLoginType("0");
            }
            if ("0".equals(loginInfo.getLoginType())) {
                BaseUser user=baseUsers.get(0);
                if("0".equals(user.getState())){
                    return ResultUtil.data(ResultCode.LOCK_ERROR.getCode(), ResultCode.LOCK_ERROR.getMes(), null);
                }

                Rsa rsa = rsaMapper.selectById("1");
                String privateKey=rsa.getPrivateKey();
                String passWord = RSAUtil.decrypt1(loginInfo.getPassword(), privateKey);

                if (!baseUsers.get(0).getPassword().equals(Md5Util.hash(passWord))) {

                    Integer loginNumber=user.getLoginNumber();
                    if(loginNumber >= 2){
                        user.setState("0");
                    }
                    loginNumber++;
                    user.setLoginNumber(loginNumber);
                    userMapper.updateById(user);
                    return ResultUtil.data(ResultCode.PASSWORD_ERROR.getCode(), ResultCode.PASSWORD_ERROR.getMes(), null);
                }

                user.setState("1");
                user.setLoginNumber(0);
                userMapper.updateById(user);
            }
            if ("1".equals(loginInfo.getLoginType())) {
                //String requestId = request.getHeader("x-request-id");
                String vcode = (String) redisUtil.get("mobileCode:" + loginInfo.getUsername());
                if (StringUtils.isEmpty(vcode) || !vcode.equals(loginInfo.getCode())) {
                    return ResultUtil.data(ResultCode.MOBILE_CODE_ERROR.getCode(), "验证码不正确", null);
                }
            }




            BaseUser updateTime = new BaseUser();
            updateTime.setLastLoginTime(LocalDateTime.now());
            updateTime.setId(baseUsers.get(0).getId());
            userMapper.updateById(updateTime);


            UserInfo userInfo = new UserInfo();

            if ("ADMIN".equals(loginInfo.getFrom())) {
                if ("admin".equals(baseUsers.get(0).getUsername())) {
                    QueryWrapper<Function> functionQueryWrapper = new QueryWrapper<Function>();
                    functionQueryWrapper.eq("clientType", loginInfo.getFrom());
                    functionQueryWrapper.eq("state", "1");
                    functionQueryWrapper.orderByAsc("sort");
                    List<Function> functions = functionMapper.selectList(functionQueryWrapper);
                    userInfo.setResouces(functions);
                    userInfo.setRole("admin");
                } else {
                    QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<UserRole>();
                    userRoleQueryWrapper.eq("userId", baseUsers.get(0).getId());
                    List<UserRole> userRoles = userRoleMapper.selectList(userRoleQueryWrapper);
                    List<Long> roleIds = new ArrayList<Long>();
                    for (UserRole userRole : userRoles) {
                        roleIds.add(userRole.getRoleId());
                    }
                    if (roleIds.size() > 0) {
                        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<Role>();
                        roleQueryWrapper.in("id", roleIds);
                        //roleQueryWrapper.eq("name", "admin");
                        List<Role> roleList = roleMapper.selectList(roleQueryWrapper);
                        if (roleList != null && roleList.size() > 0) {
                            //userInfo.setRole("admin");


                            QueryWrapper<RoleFunction> roleFunctionQueryWrapper = new QueryWrapper<RoleFunction>();
                            roleFunctionQueryWrapper.in("roleId", roleIds);
                            List<RoleFunction> roleFunctions = roleFunctionMapper.selectList(roleFunctionQueryWrapper);
                            List<String> functionIds = new ArrayList<String>();
                            for (RoleFunction roleFunction : roleFunctions) {
                                functionIds.add(roleFunction.getFunctionId());
                            }
                            if (BaseUtil.listIsNotNullElement(functionIds)) {

                                QueryWrapper<Function> functionQueryWrapper = new QueryWrapper<Function>();
                                functionQueryWrapper.eq("clientType", loginInfo.getFrom());
                                functionQueryWrapper.eq("state", "1");
                                functionQueryWrapper.in("id", functionIds);
                                List<Function> functions = functionMapper.selectList(functionQueryWrapper);
                                userInfo.setResouces(functions);
                                userInfo.setRole(roleList.get(0).getName());
                            }

                        }
                    }

                }
            }

            BeanUtils.copyProperties(baseUsers.get(0), userInfo);


            if (saveUserInfo(userInfo, loginInfo)) {
                return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, userInfo);
            } else {
                //if("WEB".equals(loginInfo.getFrom())) {

                //}
                return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), null, null);
            }
        }

    }

    private Result<UserInfo> ValidateParam(LoginInfo loginInfo) {
        String from = loginInfo.getFrom();
        if (StringUtils.isEmpty(from) || !ClientType.hasKey(from)) {
            return ResultUtil.data(ResultCode.FROM_ERROR.getCode(), ResultCode.FROM_ERROR.getMes(), null);
        }
        return null;
    }

    private boolean saveUserInfo(UserInfo userInfo, LoginInfo loginInfo) {
        String userInfoKey = TokenInfo.getKey(userInfo.getId().toString(), loginInfo.getFrom());
        userInfo.setFrom(loginInfo.getFrom());
        String token = JwtUtil.buildJWT(userInfo.getFrom(), userInfo.getId().toString(), JwtUtil.JWT_DURATION);
        userInfo.setFrom(loginInfo.getFrom());
        userInfo.setToken(token);
        return redisUtil.set(userInfoKey, userInfo, JwtUtil.JWT_DURATION);
    }

    @Override
    public Result<String> refToken(String token) {
        Map<String, Object> parseJWT1 = JwtUtil.parseJWT(JwtUtil.generateKey(JwtUtil.JWT_ALG, JwtUtil.JWT_RULE), token);
        Result<String> result = null;
        if (!(boolean) parseJWT1.get("result")) {
            String code = parseJWT1.get("code").toString();
            ResultCode valueOf = ResultCode.valueOf(code);
            if (valueOf.getCode().equals(ResultCode.TOKEN_EXPIREDJWT.getCode())) {
                try {
                    return checkExpriToken(valueOf, token);
                } catch (UnsupportedEncodingException e) {
                    return ResultUtil.data(valueOf.getCode(), valueOf.getMes(), null);
                }

            } else {
                result = ResultUtil.data(valueOf.getCode(), valueOf.getMes(), null);
            }
        } else {
            @SuppressWarnings("unchecked")
            Jws<Claims> parseJWT = (Jws<Claims>) parseJWT1.get("code");
            String userId = parseJWT.getBody().getId();
            String subject = parseJWT.getBody().getSubject();
            TokenInfo tokenInfo = new TokenInfo(userId, subject);

            boolean hasKey = redisUtil.hasKey(tokenInfo.getKey());
            if (hasKey) {
                UserInfo userInfo = (UserInfo) redisUtil.get(tokenInfo.getKey());
                if (!userInfo.getToken().equals(token)) {
                    return ResultUtil.data(ResultCode.TOKEN_SIGNATURE.getCode(), ResultCode.TOKEN_SIGNATURE.getMes(),
                            null);
                }
            }
            String refToken = createToken(tokenInfo);
            result = ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), ResultCode.RESULT_SUCCESS.getMes(), refToken);
        }
        return result;
    }

    @Override
    public Result<String> logout(String token) {
        Map<String, Object> parseJWT1 = JwtUtil.parseJWT(JwtUtil.generateKey(JwtUtil.JWT_ALG, JwtUtil.JWT_RULE), token);
        Result<String> result = null;
        @SuppressWarnings("unchecked")
        Jws<Claims> parseJWT = (Jws<Claims>) parseJWT1.get("code");
        String userId = parseJWT.getBody().getId();
        String subject = parseJWT.getBody().getSubject();
        String key = TokenInfo.getKey(userId, subject);
        redisUtil.del(key);
        result = ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), ResultCode.RESULT_SUCCESS.getMes(), null);

        return result;
    }

    private String createToken(TokenInfo tokenInfo) {
        String token = JwtUtil.buildJWT(tokenInfo.getFrom(), tokenInfo.getId(), JwtUtil.JWT_DURATION);
        BaseUser baseUser = userMapper.selectById(tokenInfo.getId());
        UserInfo userInfo = new UserInfo();
        if ("ADMIN".equals(tokenInfo.getFrom())) {
            if ("admin".equals(baseUser.getUsername())) {
                QueryWrapper<Function> functionQueryWrapper = new QueryWrapper<Function>();
                functionQueryWrapper.eq("clientType", tokenInfo.getFrom());
                functionQueryWrapper.eq("state", "1");
                functionQueryWrapper.orderByAsc("sort");
                List<Function> functions = functionMapper.selectList(functionQueryWrapper);
                userInfo.setResouces(functions);
                userInfo.setRole("admin");
            } else {
                QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<UserRole>();
                userRoleQueryWrapper.eq("userId", baseUser.getId());
                List<UserRole> userRoles = userRoleMapper.selectList(userRoleQueryWrapper);
                List<Long> roleIds = new ArrayList<Long>();
                for (UserRole userRole : userRoles) {
                    roleIds.add(userRole.getRoleId());
                }
                if (roleIds.size() > 0) {
                    QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<Role>();
                    roleQueryWrapper.in("id", roleIds);
                    //roleQueryWrapper.eq("name", "admin");
                    List<Role> roleList = roleMapper.selectList(roleQueryWrapper);
                    if (roleList != null && roleList.size() > 0) {
                        //userInfo.setRole("admin");


                        QueryWrapper<RoleFunction> roleFunctionQueryWrapper = new QueryWrapper<RoleFunction>();
                        roleFunctionQueryWrapper.in("roleId", roleIds);
                        List<RoleFunction> roleFunctions = roleFunctionMapper.selectList(roleFunctionQueryWrapper);
                        List<String> functionIds = new ArrayList<String>();
                        for (RoleFunction roleFunction : roleFunctions) {
                            functionIds.add(roleFunction.getFunctionId());
                        }
                        QueryWrapper<Function> functionQueryWrapper = new QueryWrapper<Function>();
                        functionQueryWrapper.eq("clientType", tokenInfo.getFrom());
                        functionQueryWrapper.eq("state", "1");
                        functionQueryWrapper.in("id", functionIds);
                        List<Function> functions = functionMapper.selectList(functionQueryWrapper);
                        userInfo.setResouces(functions);

                    }
                }

            }
        }
        BeanUtils.copyProperties(baseUser, userInfo);

        userInfo.setFrom(tokenInfo.getFrom());
        // info.setResouces(null);
        userInfo.setToken(token);
        String key = TokenInfo.getKey(tokenInfo.getId(), tokenInfo.getFrom());
        redisUtil.set(key, userInfo);
        redisUtil.expire(key, JwtUtil.JWT_DURATION);
        return token;
    }

    public Result<String> checkExpriToken(ResultCode code, String token) throws UnsupportedEncodingException {
        TokenInfo info = JwtUtil.parseExpriToken(token);
        if (info != null) {
            boolean hasKey = ClientType.hasKey(info.getFrom() == null ? "test" : info.getFrom());
            if (hasKey && info.getId() != null) {
                String refToken = createToken(info);
                return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, refToken);
            } else {
                return ResultUtil.data(code.getCode(), code.getMes(), null);
            }

        } else {
            return ResultUtil.data(code.getCode(), code.getMes(), null);
        }

    }

//	@Transactional(rollbackFor = Exception.class)
//	@Override
//	public boolean saveOrUpdate(EditUser entity) {
//		int rows = 0;
//		try {
//			BaseUser baseUser = new BaseUser();
//			BeanUtils.copyProperties(entity, baseUser);
//			if (entity.getId() == null) {
//				baseUser.setCreateTime(LocalDateTime.now());
//				rows = userMapper.insert(baseUser);
//			} else {
//				baseUser.setUpdateTime(LocalDateTime.now());
//				rows = userMapper.updateById(baseUser);
//			}
//			if (rows > 0 && entity.getRoles() != null && entity.getRoles().size() > 0) {
//				for (String roleId : entity.getRoles()) {
//					UserRole uRole = new UserRole();
//					uRole.setUserId(baseUser.getId());
//					uRole.setRoleId(Long.parseLong(roleId));
//					userRoleMapper.insert(uRole);
//				}
//				return true;
//			} else {
//				return rows>0;
//			}
//		} catch (Exception e) {
//			return false;
//		}
//	}

    @Override
    public List<UserClassify> getUserClassify(UserInfo loginInfo) {
        //获取用户角色
        QueryWrapper<UserRole> userRoleQw = new QueryWrapper<UserRole>();
        userRoleQw.eq("userId", loginInfo.getId());
        List<UserRole> userRoles = userRoleMapper.selectList(userRoleQw);
        List<UserClassify> dataPrivilege = null;
        if (BaseUtil.listIsNotNullElement(userRoles)) {
            QueryWrapper<UserClassify> ucQw = new QueryWrapper<UserClassify>();
            ucQw.eq("roleId", userRoles.get(0).getRoleId());
            dataPrivilege = userClassifyMapper.selectList(ucQw);

        }
        return dataPrivilege;
    }


    @Override
    public Classifys buildUserClassifys(UserInfo loginInfo) {
        List<UserClassify> dataPrivilege = this.getUserClassify(loginInfo);

        //获取数据权限
        List<Long> afIds = new ArrayList<>();//全宗ids
        List<Long> categoryIds = new ArrayList<>();//门类ids
        List<Long> classIds = new ArrayList<>();//类目ids
        List<String> fieldYearIds = new ArrayList<>();//字段年度ids

        for(int i=0;i<dataPrivilege.size();i++){
            UserClassify ucBean=dataPrivilege.get(i);
            if (ucBean.getType() == UserClassifyType.LEVEL_1.getKey()) afIds.add(ucBean.getClassifyId());
            else if (ucBean.getType() == UserClassifyType.LEVEL_2.getKey()) categoryIds.add(ucBean.getClassifyId());
            else if (ucBean.getType() == UserClassifyType.LEVEL_3.getKey()) classIds.add(ucBean.getClassifyId());
            else if (ucBean.getField()!=null && ucBean.getType() == UserClassifyType.LEVEL_4.getKey() && ucBean.getField().equals("archivalYear"))
                fieldYearIds.add(ucBean.getFieldValue());
        }

        Classifys c = new Classifys();
        c.setFonds(afIds);
        c.setCategoryIds(categoryIds);
        c.setClassIds(classIds);
        c.setFieldYearIds(fieldYearIds);
        return c;
    }


    @Override
    public Classifys buildUserDeptPermissions(UserInfo loginInfo) {

        //获取数据权限
        List<Long> afIds = new ArrayList<>();//全宗ids
        QueryWrapper<Dept> qw = new QueryWrapper<Dept>();
        qw.in("id", loginInfo.getDeptIds());
        List<Dept> depts = deptMapper.selectList(qw);

        depts.forEach(d -> {
            afIds.add(d.getFondsId());
        });
        List<UserClassify> dataPrivilege = this.getUserClassify(loginInfo);

        Classifys c = new Classifys();
        c.setFonds(afIds);
        return c;
    }


    @Override
    public List<BaseUser> gainDeptPostUser(Map<String, Object> param) {
        return baseMapper.queryDeptPostUser(param);
    }

    @Override
    public String gainDeptNameByUserId(String userId) {
        List<UserDept> udList = userDeptMapper.selectList(new QueryWrapper<UserDept>().eq("userId", userId));
        StringBuffer sb = new StringBuffer();

        if(udList.size()<=0){
            return null;
        }
        udList.forEach((UserDept ud) -> {
            Dept dept = deptMapper.selectById(ud.getDeptId());
            sb.append(dept.getDeptName()).append(",");
        });
        String deptStr = sb.deleteCharAt(sb.length() - 1).toString();

        return deptStr;
    }

    @Override
    public void buildFunction(UserInfo loginUser) {
        if ("admin".equals(loginUser.getUsername()) && !RedisUtil.isAppoint(VersionsMarkType.VERSIONS_4)) {
            QueryWrapper<Function> functionQueryWrapper = new QueryWrapper<Function>();
            functionQueryWrapper.eq("clientType", "ADMIN");
            functionQueryWrapper.eq("state", "1");
            functionQueryWrapper.orderByAsc("sort");
            List<Function> functions = functionMapper.selectList(functionQueryWrapper);
            loginUser.setResouces(functions);
            loginUser.setRole("admin");
//				userInfoNew.setResouces(functions);
//				userInfoNew.setRole("admin");
        } else {
            QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<UserRole>();
            userRoleQueryWrapper.eq("userId", loginUser.getId());
            List<UserRole> userRoles = userRoleMapper.selectList(userRoleQueryWrapper);
            List<Long> roleIds = new ArrayList<Long>();
            for (UserRole userRole : userRoles) {
                roleIds.add(userRole.getRoleId());
            }
            if (roleIds.size() > 0) {
                QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<Role>();
                roleQueryWrapper.in("id", roleIds);
                //roleQueryWrapper.eq("name", "admin");
                List<Role> roleList = roleMapper.selectList(roleQueryWrapper);
                if (roleList != null && roleList.size() > 0) {
                    //userInfo.setRole("admin");

                    loginUser.setRole(roleList.get(0).getName());

                    QueryWrapper<RoleFunction> roleFunctionQueryWrapper = new QueryWrapper<RoleFunction>();
                    roleFunctionQueryWrapper.in("roleId", roleIds);
                    List<RoleFunction> roleFunctions = roleFunctionMapper.selectList(roleFunctionQueryWrapper);
                    List<String> functionIds = new ArrayList<String>();
                    for (RoleFunction roleFunction : roleFunctions) {
                        functionIds.add(roleFunction.getFunctionId());
                    }

                    if (BaseUtil.listIsNotNullElement(functionIds)) {
                        QueryWrapper<Function> functionQueryWrapper = new QueryWrapper<Function>();
//							functionQueryWrapper.eq("clientType", "ADMIN");
                        functionQueryWrapper.eq("clientType", "ADMIN");
                        functionQueryWrapper.eq("state", "1");
                        functionQueryWrapper.in("id", functionIds);
                        List<Function> functions = functionMapper.selectList(functionQueryWrapper);
//							userInfoNew.setResouces(functions);
                        loginUser.setResouces(functions);
                    }

                }
            }

        }
    }

    @Override
    public Result<String> verifyUserPost(BaseUser baseUser, List<String> postIds) {

        List<BaseUser> baseUserList = new ArrayList<>();
        postIds.forEach((String postId) -> {
            Map param = new HashMap();
            List<String> deptIds = new ArrayList<>();
            Post post = postMapper.selectById(postId);

            if (null != post && null != baseUser.getDeptIds()) {
                if (post.getCode().equals("deptLeader")) {
                    param.put("postCode", post.getCode());
                    param.put("deptIds", Arrays.asList(baseUser.getDeptIds().toString().split(",")));
                } else {
                    Dept dept = deptMapper.selectById(baseUser.getDeptIds());
                    //获取全公司的部门id
                    List<Dept> deptList = new ArrayList<>();
                    String[] d = dept.getPids().split("/");
                    if (d.length > 0 && d.length > 2) {
                        deptList = deptMapper.selectList(new QueryWrapper<Dept>().like("pids", d[1]));
                    } else {
                        deptList = deptMapper.selectList(new QueryWrapper<Dept>().like("pids", d[0]));
                    }

                    deptList.forEach((Dept de) -> {
                        deptIds.add(de.getId().toString());
                    });

                    param.put("postCode", post.getCode());
                    param.put("deptIds", deptIds);
                }
                param.put("activeUserId",baseUser.getId());
                baseUserList.addAll(baseMapper.queryDeptPostUser(param));
            }

        });
        if (BaseUtil.listIsNotNullElement(baseUserList)) {
            return ResultUtil.error("违反岗位唯一性，数量："+baseUserList.size());
        }

        return ResultUtil.success();


    }

    @Override
    public void saveUserRelevance(EditUser entity) {

        userRoleMapper.delete(new QueryWrapper<UserRole>().eq("userId",entity.getId()));
        userFondsMapper.delete(new QueryWrapper<UserFonds>().eq("userId",entity.getId()));
        userDeptMapper.delete(new QueryWrapper<UserDept>().eq("userId",entity.getId()));
        userPostMapper.deleteById(entity.getId());


        //角色
        List<String> roles = entity.getRoles();
        if (roles != null && roles.size() > 0) {
            for (String string : roles) {
                UserRole userRoleEntity = new UserRole();
                userRoleEntity.setRoleId(Long.parseLong(string));
                userRoleEntity.setUserId(entity.getId());
                userRoleMapper.insert(userRoleEntity);
            }
        }

        //全宗
        List<String> fonds = entity.getFonds();
        if (fonds != null && fonds.size() > 0) {
            for (String string : fonds) {
                UserFonds userFondsEntity = new UserFonds();
                userFondsEntity.setFondsId(string);
                userFondsEntity.setUserId(entity.getId());
                userFondsMapper.insert(userFondsEntity);
            }
        }

        List<String> depts = entity.getDepts();
        if (depts != null && depts.size() > 0) {

            userDeptMapper.delete(new QueryWrapper<UserDept>().eq("userId",entity.getId()));
            //userDeptMapper.deleteById(new QueryWrapper<UserDept>().eq("userId",entity.getId()));
            for (String string : depts) {
                UserDept userDeptEntity = new UserDept();
                userDeptEntity.setDeptId(Long.parseLong(string));
                userDeptEntity.setUserId(entity.getId());
                userDeptMapper.insert(userDeptEntity);
            }
        }

        //岗位
        List<String> posts = entity.getPosts();
        if (posts != null && posts.size() > 0) {
            for (String string : posts) {
                UserPost userPostEntity = new UserPost();
                userPostEntity.setId(entity.getId());
                userPostEntity.setPostId(Long.parseLong(string));
                userPostMapper.insert(userPostEntity);
            }
        }
    }

    @Scheduled(cron = "0 30 23 ? * SUN")
    @Async("cloudExecutor")
    @Transactional(rollbackFor = Exception.class)
    public void syncUserInfoNewScheduled(){
        if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5)) {
            String nowTime= DateUtil.getCurrentTime(DateUtil.DateFormat.YYYY_MM_DD_HH_mm_ss);
            String subTime=DateUtil.subDayOfMonth(nowTime, DateUtil.DateFormat.YYYY_MM_DD_HH_mm_ss,7);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = format.parse(subTime);
                syncUserInfoNew(date);
            }catch (ParseException e){
                e.printStackTrace();
            }
        }

    }

    public void syncUserInfoNew(Date date){
        List<User> listUser = SdkUtil.getSdkUserAll(date);

        if(listUser.size()<=0){
            System.out.println("===========没有要更新的外部用户信息========");
            return;
        }

        List<String> notIds=new ArrayList<>();
        for(int i=0;i<listUser.size();i++){
            User user = listUser.get(i);

            if(!user.getPerStatus().equals("1")){
                notIds.add(user.getPersonId());
                continue;
            }

            QueryWrapper<BaseUser> baseUserQueryWrapper = new QueryWrapper<BaseUser>();
            baseUserQueryWrapper.eq("extId", user.getPersonId());
            BaseUser bean = userMapper.selectOne(baseUserQueryWrapper);
            if (null == bean) {
                bean = new BaseUser();
                bean.setExtId(user.getPersonId());
            }
            bean.setRealName(user.getPerName());
            bean.setUsername(user.getLoginName());
            bean.setState(user.getPerStatus());
            bean.setDeptIds(Long.parseLong(user.getDeptId()));

            //保存人员数据
            saveOrUpdate(bean);

            QueryWrapper<UserDept> udQw = new QueryWrapper<>();
            udQw.eq("userId", bean.getId());
            UserDept ud = userDeptMapper.selectOne(udQw);
            if (null == ud) {
                ud = new UserDept();
                ud.setUserId(bean.getId());
                ud.setDeptId(Long.parseLong(user.getDeptId()));
                userDeptMapper.insert(ud);
            }else{
                ud.setDeptId(Long.parseLong(user.getDeptId()));
                userDeptMapper.updateById(ud);
            }
        }

        //删除被禁用的用户数据
        if(notIds.size()>0){
            QueryWrapper<BaseUser> buQw = new QueryWrapper<>();
            buQw.in("extId",notIds);
            List<BaseUser> buList = userMapper.selectList(buQw);

            List<Long> userIds=new ArrayList<>();
            for (int i=0;i<buList.size();i++){
                userIds.add(buList.get(i).getId());
            }
            if(userIds.size()>0){
                QueryWrapper<UserDept> udQw = new QueryWrapper<>();
                udQw.in("userId", userIds);
                userDeptMapper.delete(udQw);

                QueryWrapper<UserRole> urQw = new QueryWrapper<>();
                urQw.in("userId",userIds);
                userRoleMapper.delete(urQw);

                QueryWrapper<UserPost> uPQw = new QueryWrapper<>();
                uPQw.in("id",userIds);
                userPostMapper.delete(uPQw);
            }
            userMapper.delete(buQw);
        }

    }

    public void buildUserRole(Role role){
        //根据全宗Id查询到对应的分公司
        QueryWrapper<Dept> deptWrapper=new QueryWrapper<>();
        if (RedisUtil.isAppoint(VersionsMarkType.VERSIONS_5)) {
            deptWrapper.eq("parentId",1);
        }else{
            deptWrapper.eq("parentId",0);
        }
        deptWrapper.eq("fondsId",role.getFondsId());
        Dept dept= deptMapper.selectOne(deptWrapper);

        if(dept==null){
            return;
        }

        QueryWrapper<Dept> deptWrapper1=new QueryWrapper<>();
        deptWrapper1.like("pids",dept.getDeptCode());
        List<Dept> deptList = deptMapper.selectList(deptWrapper1);
        List<Long> ids=new ArrayList<>();
        for(int i=0;i<deptList.size();i++){
            ids.add(deptList.get(i).getId());
        }
        //根据对应分公司查询到对应的用户
        if(ids.size()>0){
            QueryWrapper<BaseUser> userWrapper=new QueryWrapper<>();
            userWrapper.in("deptIds",ids);
            List<BaseUser> userList = userMapper.selectList(userWrapper);
            //将用户的角色设置为普通用户
            for(int i=0;i<userList.size();i++){
                BaseUser user=userList.get(i);
                //不存在角色的用户设置为普通用户
                QueryWrapper<UserRole> urWrapper=new QueryWrapper<>();
                urWrapper.eq("userId",user.getId());
                UserRole userRole = userRoleMapper.selectOne(urWrapper);
                if(userRole==null){
                    userRole=new UserRole();
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(role.getId());
                    userRoleMapper.insert(userRole);
                }
            }
        }
    }

    /*public static void main(String[] args) {
        System.out.println(Md5Util.hash("admin"));
    }*/
}
